import 'package:flutter/foundation.dart';
import '../models/user.dart';
import '../services/user_service.dart';

/// 认证状态管理Provider
class AuthProvider extends ChangeNotifier {
  User? _currentUser;
  bool _isLoading = false;
  String? _errorMessage;
  final UserService _userService = UserService();

  /// 当前用户
  User? get currentUser => _currentUser;

  /// 是否已登录
  bool get isLoggedIn => _currentUser != null;

  /// 是否为管理员
  bool get isAdmin => _currentUser?.isAdmin ?? false;

  /// 是否为普通用户
  bool get isUser => _currentUser?.isUser ?? false;

  /// 是否正在加载
  bool get isLoading => _isLoading;

  /// 错误信息
  String? get errorMessage => _errorMessage;

  /// 用户登录
  Future<bool> login(String username, String password) async {
    _setLoading(true);
    _clearError();

    try {
      print('🔍 AuthProvider: 开始登录验证 - username=$username');
      final user = await _userService.validateLogin(username, password);
      
      if (user != null) {
        print('✅ AuthProvider: 登录成功 - username=${user.username}, role=${user.role}');
        _currentUser = user;
        _setLoading(false);
        notifyListeners();
        return true;
      } else {
        print('❌ AuthProvider: 登录失败 - 用户名或密码错误');
        _setError('用户名或密码错误');
        _setLoading(false);
        return false;
      }
    } catch (e) {
      print('❌ AuthProvider: 登录异常 - $e');
      _setError('登录失败: $e');
      _setLoading(false);
      return false;
    }
  }

  /// 用户登出
  Future<void> logout() async {
    _currentUser = null;
    _clearError();
    notifyListeners();
  }

  /// 更新当前用户信息
  Future<void> updateCurrentUser() async {
    if (_currentUser?.id != null) {
      final updatedUser = await _userService.getUserById(_currentUser!.id!);
      if (updatedUser != null) {
        _currentUser = updatedUser;
        notifyListeners();
      }
    }
  }

  /// 修改密码
  Future<bool> changePassword(String oldPassword, String newPassword) async {
    if (_currentUser?.id == null) {
      _setError('用户未登录');
      return false;
    }

    _setLoading(true);
    _clearError();

    try {
      final success = await _userService.changePassword(
        _currentUser!.id!,
        oldPassword,
        newPassword,
      );

      if (success) {
        // 更新用户信息
        await updateCurrentUser();
        _setLoading(false);
        return true;
      } else {
        _setError('原密码错误');
        _setLoading(false);
        return false;
      }
    } catch (e) {
      _setError('修改密码失败: $e');
      _setLoading(false);
      return false;
    }
  }

  /// 重置密码
  Future<bool> resetPassword(int userId, String newPassword) async {
    _setLoading(true);
    _clearError();

    try {
      final success = await _userService.resetPassword(userId, newPassword);
      _setLoading(false);
      return success;
    } catch (e) {
      _setError('重置密码失败: $e');
      _setLoading(false);
      return false;
    }
  }

  /// 获取所有用户
  Future<List<User>> getAllUsers() async {
    return await _userService.getAllUsers();
  }

  /// 创建用户
  Future<bool> createUser(User user) async {
    _setLoading(true);
    _clearError();

    try {
      final success = await _userService.createUser(user);
      _setLoading(false);
      
      if (!success) {
        _setError('创建用户失败，用户名可能已存在');
      }
      
      return success;
    } catch (e) {
      _setError('创建用户失败: $e');
      _setLoading(false);
      return false;
    }
  }

  /// 更新用户
  Future<bool> updateUser(User user) async {
    _setLoading(true);
    _clearError();

    try {
      final success = await _userService.updateUser(user);
      _setLoading(false);
      
      if (!success) {
        _setError('更新用户失败');
      }
      
      return success;
    } catch (e) {
      _setError('更新用户失败: $e');
      _setLoading(false);
      return false;
    }
  }

  /// 删除用户
  Future<bool> deleteUser(int userId) async {
    _setLoading(true);
    _clearError();

    try {
      final success = await _userService.deleteUser(userId);
      _setLoading(false);
      
      if (!success) {
        _setError('删除用户失败');
      }
      
      return success;
    } catch (e) {
      _setError('删除用户失败: $e');
      _setLoading(false);
      return false;
    }
  }

  /// 切换用户状态
  Future<bool> toggleUserStatus(int userId) async {
    _setLoading(true);
    _clearError();

    try {
      final success = await _userService.toggleUserStatus(userId);
      _setLoading(false);
      
      if (!success) {
        _setError('切换用户状态失败');
      }
      
      return success;
    } catch (e) {
      _setError('切换用户状态失败: $e');
      _setLoading(false);
      return false;
    }
  }

  /// 搜索用户
  Future<List<User>> searchUsers(String keyword) async {
    return await _userService.searchUsers(keyword);
  }

  /// 获取用户统计信息
  Future<Map<String, int>> getUserStatistics() async {
    return await _userService.getUserStatistics();
  }

  /// 设置加载状态
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  /// 设置错误信息
  void _setError(String error) {
    _errorMessage = error;
    notifyListeners();
  }

  /// 清除错误信息
  void _clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  /// 清除所有状态
  void clear() {
    _currentUser = null;
    _isLoading = false;
    _errorMessage = null;
    notifyListeners();
  }
} 